package com.cht.commonUtil.infra;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.jqGrid.ResultTableSet;
import com.cht.commonUtil.jqGrid.Rows;
import com.cht.commonUtil.structure.InfoStruc;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class QueryEnv extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		response.setCharacterEncoding( SP.UIcodeSet );
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		String sql = "";
		String fromCall = request.getParameter("fc");
		ArrayList<InfoStruc> infoStrucs = new ArrayList<InfoStruc>();
		List<DevOpsEnv> does = new ArrayList<DevOpsEnv>();
		
		String subsysId = request.getParameter("subsysId");
		ResultTableSet resultTableSet = new ResultTableSet();
		
		if ("raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
			sql = "SELECT COUNT(*) FROM env";
		} else {
			sql = "SELECT COUNT(*) FROM env WHERE subsysid=?";
		}
		
		
		
		String sord = request.getParameter("sord");
		String sidx =  request.getParameter("sidx");
		
		int total_pages = 1;
		int count  = 0; 
		int page = 1;
		int limit = 10;
		
		if ("".equalsIgnoreCase(sidx)|| sidx==null) {
			sidx = "envname";
		} 
		if ("".equalsIgnoreCase(sord)|| sord==null) {
			sord = "ASC";
		} else {
			page = Integer.parseInt(request.getParameter("page"));
			limit = Integer.parseInt(request.getParameter("rows"));
		}
		
		try {
			conn = Widgets.getConn();	
			ps = conn.prepareStatement(sql);
			if (!"raiseDeplyByDelivery".equalsIgnoreCase(fromCall) && !"reDep".equalsIgnoreCase(fromCall)) {
				ps.setString(1, subsysId);	
			}
			rs = ps.executeQuery();
			rs.next();
			count  = rs.getInt(1);
			rs.close();
			ps.close();
			if ( count  != 0 ) {
				
				if (limit  < count) {
					total_pages = (count / limit)+1;	
				}
				if ("raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
					sql = "SELECT DISTINCT envid, envname FROM env";
				} else {
					if ( conn.getMetaData().getDatabaseProductName().contains( "MySQL" ) ) {
						sql = "SELECT t1.envid,t1.envname,t1.isReloadConfirmNeed,t1.isArtificialCheckNeed,t1.isPerformHTTPD,t1.selfClass,t1.preClass,t1.creator, t1.createdDateTime FROM env t1 WHERE t1.subsysid=? ORDER BY "+sidx+" "+sord+" LIMIT "+(limit*page-limit)+","+ limit;
					} else if ( conn.getMetaData().getDatabaseProductName().contains( "Informix" ) ) {
						sql = "SELECT SKIP "+(limit*page-limit)+" FIRST "+ limit +" t1.envid,t1.envname,t1.webconsolesn AS wcsn,t1.selfClass,t1.preClass,t1.creator, t1.createdDateTime,t2.webconsoleip AS wcip FROM env t1,OUTER wcl t2 WHERE t1.subsysid=? AND t1.subsysid=t2.subsysid AND t1.webconsolesn=t2.webconsolesn ORDER BY "+sidx+" "+sord;
					}
				}
				ps = conn.prepareStatement(sql);
				if (!"raiseDeplyByDelivery".equalsIgnoreCase(fromCall) && !"reDep".equalsIgnoreCase(fromCall)) {
					ps.setString(1,subsysId);
				}
				rs = ps.executeQuery();
				ArrayList<Rows> rows = new ArrayList<Rows>();
				
				while ( rs.next() ) {
					String envid = rs.getString("envid");
					
					if ("mappingEnvSquad".equalsIgnoreCase(fromCall) || "raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
						InfoStruc infoStruc = new InfoStruc();
						infoStruc.setId( rs.getString("envid") );
						infoStruc.setName( rs.getString("envname") );
						infoStrucs.add(infoStruc);
					} else if ( "selEnvBySubSys".equalsIgnoreCase(fromCall) ||"mappingSquadHost".equalsIgnoreCase(fromCall) ) {
						DevOpsEnv doe = new DevOpsEnv();
						doe.setEnvId( rs.getString("envid") );
						doe.setEnvName( rs.getString("envname") );
						doe.setReloadConfirmNeed( rs.getString("isReloadConfirmNeed") );
						doe.setArtificialCheckNeed( rs.getString("isArtificialCheckNeed") );
						doe.setIsPerformHTTPD( rs.getString("isPerformHTTPD")  );
						does.add(doe);
					} else {
						Rows row = new Rows();
						row.setId(envid);
						String[] cell = new String[5];
						cell[0] = envid;
						cell[1] = rs.getString("envname");
						cell[2] = rs.getString("wcip")==null?"無設定":rs.getString("wcip");
						cell[3] = String.valueOf( rs.getInt("selfClass") ) ;
						cell[4] = String.valueOf( rs.getInt("preClass") ) ;
						
						row.setCell(cell);
						rows.add(row);	
					}
				}
				resultTableSet.setRows( rows );
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
				
			} else {
				page =0;
				total_pages=0;
				resultTableSet.setPage( String.valueOf(page) );
				resultTableSet.setTotal( total_pages );
				resultTableSet.setRecords( String.valueOf(count) );
			}
		} catch ( Exception e) {
			Widgets.errLog(e);
		} finally {
			try {
				if (rs != null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		if ( "mappingEnvSquad".equalsIgnoreCase(fromCall) || "raiseDeplyByDelivery".equalsIgnoreCase(fromCall) || "reDep".equalsIgnoreCase(fromCall)) {
			response.getWriter().write( new Gson().toJson(infoStrucs) );
		} else if( "selEnvBySubSys".equalsIgnoreCase(fromCall) || "mappingSquadHost".equalsIgnoreCase(fromCall) ) {
			response.getWriter().write( new Gson().toJson(does) );
		} else {
			response.getWriter().write( new Gson().toJson(resultTableSet) );	
		}
	}

}

class DevOpsEnv {
	private String envId;					
	private String envName;
	private String isArtificialCheckNeed;
	private String isReloadConfirmNeed;
	private String isPerformHTTPD;
	
	public String getIsArtificialCheckNeed() {
		return isArtificialCheckNeed;
	}
	public void setIsArtificialCheckNeed(String isArtificialCheckNeed) {
		this.isArtificialCheckNeed = isArtificialCheckNeed;
	}
	public String getIsReloadConfirmNeed() {
		return isReloadConfirmNeed;
	}
	public void setIsReloadConfirmNeed(String isReloadConfirmNeed) {
		this.isReloadConfirmNeed = isReloadConfirmNeed;
	}
	public String getIsPerformHTTPD() {
		return isPerformHTTPD;
	}
	public void setIsPerformHTTPD(String isPerformHTTPD) {
		this.isPerformHTTPD = isPerformHTTPD;
	}
	public String getEnvId() {
		return envId;
	}
	public void setEnvId(String envId) {
		this.envId = envId;
	}
	public String getEnvName() {
		return envName;
	}
	public void setEnvName(String envName) {
		this.envName = envName;
	}
	public String isArtificialCheckNeed() {
		return isArtificialCheckNeed;
	}
	public void setArtificialCheckNeed(String isArtificialCheckNeed) {
		this.isArtificialCheckNeed = isArtificialCheckNeed;
	}
	public String isReloadConfirmNeed() {
		return isReloadConfirmNeed;
	}
	public void setReloadConfirmNeed(String isReloadConfirmNeed) {
		this.isReloadConfirmNeed = isReloadConfirmNeed;
	}
}